<template>
  <div>
    <div>
      <el-tree
        ref="tree"
        v-loading="loading"
        :data="permissList"
        :props="{label : 'name'}"
        default-expand-all
        show-checkbox
        check-strictly
        node-key="id"
        style="min-height :300px"
      />
    </div>

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
import { getRoleId, assignPerm } from '@/api/setting'
export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      permissList: [], // 权限列表
      loading: false
    }
  },
  created() {
    // 调用获取权限列表
    this.getPermissionList()
    // 调用获取当前角色已有的权限
    this.getRoleId()
  },
  methods: {
    // 获取当前角色已有的权限
    async getRoleId() {
      const res = await getRoleId(this.roleId)
      // console.log(res)
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    },
    // 获取权限列表
    async getPermissionList() {
      this.loading = true
      const res = await getPermissionList()
      this.permissList = tranListToTreeData(res.data)
      this.loading = false
    },

    // 取消分配权限
    cancelButton() {
      this.$emit('close')
    },
    // 分配权限
    async setRolesBtn() {
      const permIds = this.$refs.tree.getCheckedKeys()
      const res = await assignPerm({ id: this.roleId, permIds })
      this.$message.success(res.message)
      this.$emit('close')
    }
  }
}
</script>
<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}
</style>
